namespace("sg.canvas");

/**
 *
 * @param width
 * @param height
 */
sg.canvas.Canvas = function(width, height, id) {
    this.id = id || "";
    this.domObject = document.createElement('canvas');
    this.domObject.width  = width;
    this.domObject.height = height;
    this.domObject.id = id;
    this.context2D = this.domObject.getContext("2d");
    this.drawOrder = [];
    this.placeholder = null;
};
sg.canvas.Canvas.prototype.append = function(placeholder) {
    this.placeholder = placeholder;
    placeholder.appendChild(this.domObject);
    return this;
};
sg.canvas.Canvas.prototype.drawImage = function(image, posX, posY, width, height, imgOffsetX, imgOffsetY, imgWidth, imgHeight ) {
    if(arguments.length > 5) {
       this.drawOrder.push(function() {this.context2D.drawImage(image, posX, posY, width, height, imgOffsetX, imgOffsetY, imgWidth, imgHeight)});
    }
    else {
        this.drawOrder.push(function() {this.context2D.drawImage(image, posX, posY, width, height)});
    }
    return this;
};

sg.canvas.Canvas.prototype.clear = function(posX, posY, width, height) {
    this.context2D.clearRect(posX, posY, width, height);
    return this;
};

sg.canvas.Canvas.prototype.translate = function(x, y) {
    this.drawOrder.push(function() {this.context2D.translate(x, y)});
    return this;
};

sg.canvas.Canvas.prototype.rotate = function(angle) {
    this.drawOrder.push(function() {this.context2D.rotate(angle)});
    return this;
};

sg.canvas.Canvas.prototype.save = function() {
    this.drawOrder.push(function() {this.context2D.save()});
    return this;
};

sg.canvas.Canvas.prototype.restore = function() {
    this.drawOrder.push(function() {this.context2D.restore()});
    return this;
};

sg.canvas.Canvas.prototype.scale = function(x ,y) {
    this.drawOrder.push(function() {this.context2D.scale(x, y)});
    return this;
};
sg.canvas.Canvas.prototype.transform = function(m11, m12, m21, m22, dx, dy) {
    this.drawOrder.push(function() {this.context2D.transform(m11, m12, m21, m22, dx, dy)});
    return this;
};

sg.canvas.Canvas.prototype.draw = function() {
    for(var i=0; i<this.drawOrder.length; i++) {
        this.drawOrder[i].call(this);
    }
    this.drawOrder = [];
    return this;
};
sg.canvas.Canvas.prototype.destroy = function() {
   this.placeholder.removeChild(this.domObject);
};




